/*
  User: MissingAeon
  Date: 2024/5/17
  Time: 11:53
--*/
import { defineStore } from "pinia";
import base from "@/api/base.ts";

interface UserStore {
  // 用户id
  userId: number | null;
  // 昵称
  nickname: string;
  // 手机
  phone?: string;
  // 邮箱
  email?: string;
  // 角色
  userRole?: string;
  // token
  token: string | null;
}

export const useUserStore = defineStore("user", {
  state: (): UserStore => ({
    userId: null,
    nickname: "未登录",
    token: null,
  }),
  actions: {
    /**
     * 初始化
     * @param user
     */
    initial(user: object) {
      this.$patch(user);
    },
    /**
     * 重置
     */
    reset() {
      this.$reset();
    },
  },
  getters: {
    /**
     * 添加了前缀
     */
    applyToken(): string {
      return base.tokenPrefix + this.token;
    },
    /**
     * 获取用户名
     */
    userName(): string {
      return this.nickname + base.accountSeparateChar + this.userId;
    },
  },
  persist: {
    // https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage
    storage: localStorage,
    afterRestore: (ctx) => {
      console.log(`刚刚恢复完 '${ctx.store.$id}'`);
    },
  },
});
